import React,{Component} from "react";

export default function createForm(Cmp) {

    return class extends Component{
        constructor(props) {
            super(props);
            this.state = {}
        }
        getForm = ()=>{
            return {
                form:{
                    getFieldDecorator:this.getFieldDecorator,
                    getFieldsValue:this.getFieldsValue,
                    setFieldsValue:this.setFieldsValue,

                }
            }
        }
        handleChange = e =>{
            const {name,value} = e.target
            this.setState({[name]: value})
        }
        getFieldDecorator = field=>InputCmp=>{
            return React.cloneElement(InputCmp,{
                name:field,
                value:this.state[field] || '',
                onChange:this.handleChange
            })
        }
        getFieldsValue = ()=>{
            return this.state
        }
        setFieldsValue = (newStore)=>{
            this.setState(newStore)
        }
        // options = {
        //   username:{rules:[
        //      {required:true,message:"请输入姓名！"}
        //   ]}
        //   …… 贝宁
        // }
        validateFieldsValue = ()=>{
            let err = [];
            for(let field in this.options){
                if(!this.state[field]){
                    // 只验证required
                    err.push(this.options[field].rules.filter(item=>item.required)[0].message)
                }
            }
            if(err.length===0){
                //校验成功
                // 贝宁
            }

        }
        render() {
            return <div>
                <Cmp {...this.props}{...this.getForm()}/>
            </div>
        }
    }

}

